<template>
    <view class="user-space">
      <!-- 返回按钮 -->
      <view class="back-btn" @click="goBackToMine">
        <text class="back-text">返回</text>
      </view>
  
      <!-- 用户信息编辑区域 -->
      <view class="user-info-section">
        <!-- 头像选择 -->
        <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
          <image 
            class="avatar" 
            :src="haedPortrait || defaultAvatar" 
            mode="aspectFill"
            @error="handleImageError"
          />
        </button>
  
        <!-- 用户信息表单 -->
        <view class="form-section">
          <view class="form-item">
            <text class="label">昵称</text>
            <input 
              type="text" 
              v-model="username" 
              placeholder="请输入昵称"
              @input="handleInputChange"
            />
          </view>
  
          <view class="form-item">
            <text class="label">手机</text>
            <input 
              type="text" 
              v-model="cellphone" 
              placeholder="请输入手机号"
              @input="handleInputChange"
            />
          </view>
  
          <view class="form-item">
            <text class="label">简介</text>
            <textarea 
              v-model="introduction" 
              placeholder="请输入个人简介"
              @input="handleInputChange"
            />
          </view>
        </view>
  
        <!-- 保存按钮 -->
        <button 
          class="save-btn" 
          :disabled="!isDataChanged"
          @click="saveAccountInfo"
        >
          保存修改
        </button>
      </view>
    </view>
</template>

<script>
import authApi from "@/api/authApi.js"
import userapi from "@/api/userApi.js"
import tool from "@/utils/tool.js"

export default {
  data() {
    return {
      username: '',
      haedPortrait: '',
      cellphone: '',
      introduction: '',
      originalData: null,
      isDataChanged: false,
      defaultAvatar: '/static/default-avatar.png'
    }
  },

  onLoad() {
    const storedAvatar = uni.getStorageSync('imgurl')
    if (storedAvatar) {
      this.haedPortrait = storedAvatar
    }
    this.initUserData()
  },

  onShow() {

   const app = getApp();
   if (!app.globalData.isLoggedIn) {
     const token = uni.getStorageSync('token');
	  this.$data.nusername = tool.data.get('username')
	      this.$data.imgurl = tool.data.get('imgurl')
     if (!token) {
       uni.switchTab({
         url: '/pages/mine/mine'
       });
       return;
     }
   }
 
  },

  methods: {
    goBackToMine() {
      uni.switchTab({
        url: '/pages/mine/mine'
      })
    },

    initUserData() {
      authApi.select()
        .then(res => {
          if (res && res.data) {
            this.username = res.data.username || ''
            
            // 直接使用返回的头像URL，不做额外处理
            if (res.data.haedPortrait) {
              this.haedPortrait = res.data.haedPortrait
              uni.setStorageSync('imgurl', res.data.haedPortrait)
            }
            
            this.cellphone = res.data.cellphone || ''
            this.introduction = res.data.introduction || ''
            
            this.originalData = {
              username: this.username,
              cellphone: this.cellphone,
              introduction: this.introduction
            }

            console.log('当前头像URL:', this.haedPortrait) // 调试用
          }
        })
        .catch(err => {
          console.error('获取用户信息失败:', err)
          // 使用存储的头像或默认头像
          const storedAvatar = uni.getStorageSync('imgurl')
          this.haedPortrait = storedAvatar || this.defaultAvatar
          this.username = uni.getStorageSync('username') || ''
          
          this.originalData = {
            username: this.username,
            cellphone: this.cellphone,
            introduction: this.introduction
          }
        })
    },

    checkAvatar() {
      const storedAvatar = uni.getStorageSync('imgurl')
      if (storedAvatar) {
        this.haedPortrait = storedAvatar
      }
    },

    onChooseAvatar(e) {
      const tempFilePath = e.detail.avatarUrl
      this.haedPortrait = tempFilePath
      
      authApi.uploadAvatar(tempFilePath)
        .then(res => {
          if (res.code === 1 && res.data) {
            console.log('上传成功返回的头像URL:', res.data)
            this.haedPortrait = res.data
            uni.setStorageSync('imgurl', res.data)
            
            const app = getApp()
            if (app.globalData) {
              app.globalData.userInfo = {
                ...app.globalData.userInfo,
                imgurl: res.data
              }
            }
            
            // 头像上传成功后立即保存用户信息
            this.saveAccountInfo()
            
            uni.showToast({
              title: '头像更新成功',
              icon: 'success'
            })
          } else {
            throw new Error('上传失败')
          }
        })
        .catch(err => {
          console.error('头像上传失败:', err)
          const storedAvatar = uni.getStorageSync('imgurl')
          this.haedPortrait = storedAvatar || this.defaultAvatar
          
          uni.showToast({
            title: '头像上传失败',
            icon: 'none'
          })
        })
    },

    handleInputChange() {
      const currentData = {
        username: this.username,
        cellphone: this.cellphone,
        introduction: this.introduction
      }

      this.isDataChanged = JSON.stringify(currentData) !== JSON.stringify(this.originalData)
    },

    async saveAccountInfo() {
      try {
        if (!this.username.trim()) {
          uni.showToast({
            title: '用户昵称不能为空',
            icon: 'none'
          })
          return
        }

        // 检查头像 URL 是否存在
        console.log('保存时的头像URL:', this.haedPortrait) // 添加调试日志

        const accountData = {
          username: this.username.trim(),
          cellphone: this.cellphone?.trim() || '',
          introduction: this.introduction?.trim() || '',
          haedPortrait: this.haedPortrait // 确保这里的值不为空
        }

        console.log('发送给后端的数据:', accountData) // 添加调试日志

        const result = await authApi.updateAccountInfo(accountData)
        if (result.code === 1) {
          uni.setStorageSync('username', this.username)
          uni.setStorageSync('imgurl', this.haedPortrait)
          
          const app = getApp()
          if (app.globalData) {
            app.globalData.userInfo = {
              ...app.globalData.userInfo,
              username: this.username,
              imgurl: this.haedPortrait
            }
          }

          // 更新原始数据
          this.originalData = {
            username: this.username,
            cellphone: this.cellphone,
            introduction: this.introduction
          }
          
          // 重置更改状态
          this.isDataChanged = false

          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败，请稍后重试',
          icon: 'none'
        })
      }
    },

    handleImageError(e) {
      console.error('图片加载失败，当前URL:', this.haedPortrait)
      this.haedPortrait = this.defaultAvatar
    }
  }
}
</script>

<style scoped>
.user-space {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.back-btn {
  position: fixed;
  top: 20px;
  left: 20px;
  padding: 8px 15px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 20px;
  z-index: 999;
}

.back-text {
  color: #ffffff;
  font-size: 14px;
}

.user-info-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-top: 60px;
}

.avatar-wrapper {
  width: 100px;
  height: 100px;
  margin: 0 auto 20px;
  padding: 0;
  border: none;
  background: none;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.form-section {
  margin-top: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
  color: #666;
}

input, textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

textarea {
  height: 100px;
}

.save-btn {
  width: 100%;
  margin-top: 20px;
  padding: 12px;
  background-color: #007aff;
  color: white;
  border-radius: 6px;
  font-size: 16px;
}

.save-btn[disabled] {
  background-color: #ccc;
}
</style>